<template>
  <n-layout>
    <n-layout-header bordered>
      <div class="header-content">
        <div class="logo">
          <h2>法律平台</h2>
        </div>
        <div class="nav-menu">
          <n-menu mode="horizontal" :options="menuOptions" />
        </div>
        <div class="user-actions">
          <template v-if="userStore.isLoggedIn">
            <n-dropdown :options="userMenuOptions" @select="handleUserMenuSelect">
              <n-button text>
                {{ userStore.username }}
                <template #icon>
                  <n-icon><PersonCircle /></n-icon>
                </template>
              </n-button>
            </n-dropdown>
          </template>
          <template v-else>
            <n-button text @click="showLoginModal = true">
              登录
            </n-button>
            <n-button type="primary" @click="showRegisterModal = true">
              注册
            </n-button>
          </template>
        </div>
      </div>
    </n-layout-header>

    <n-layout-content>
      <router-view></router-view>
    </n-layout-content>

    <n-layout-footer bordered>
      <div class="footer-content">
        <div class="footer-section">
          <h3>联系我们</h3>
          <p>电话：18681529205</p>
          <p>邮箱：467643531@qq.com</p>
        </div>
        <div class="footer-section">
          <h3>服务时间</h3>
          <p>周一至周五：9:00-18:00</p>
          <p>周六至周日：10:00-16:00</p>
        </div>
        <div class="footer-section">
          <h3>关于我们</h3>
          <p>专业的法律服务平台</p>
          <p>为您提供优质的法律咨询服务</p>
        </div>
      </div>
      <div class="copyright">
        2024 法律平台 All Rights Reserved
      </div>
    </n-layout-footer>
  </n-layout>

  <!-- 登录对话框 -->
  <n-modal 
    v-model:show="showLoginModal" 
    preset="card"
    title="登录" 
    style="width: 400px"
    :bordered="false"
    size="huge"
    :segmented="false"
  >
    <n-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="loginForm.username" placeholder="请输入用户名" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input v-model:value="loginForm.password" type="password" placeholder="请输入密码" />
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="showLoginModal = false">取消</n-button>
        <n-button type="primary" :loading="loginLoading" @click="handleLogin">登录</n-button>
      </n-space>
    </template>
  </n-modal>

  <!-- 注册对话框 -->
  <n-modal 
    v-model:show="showRegisterModal" 
    preset="card"
    title="注册" 
    style="width: 400px"
    :bordered="false"
    size="huge"
    :segmented="false"
  >
    <n-form ref="registerFormRef" :model="registerForm" :rules="registerRules">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="registerForm.username" placeholder="请输入用户名" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input v-model:value="registerForm.password" type="password" placeholder="请输入密码" />
      </n-form-item>
      <n-form-item label="确认密码" path="confirmPassword">
        <n-input v-model:value="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" />
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="showRegisterModal = false">取消</n-button>
        <n-button type="primary" :loading="registerLoading" @click="handleRegister">注册</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup>
import { ref, h } from 'vue'
import { useRouter } from 'vue-router'
import { 
  PersonCircle,
  HomeOutline,
  DocumentTextOutline,
  ChatbubbleEllipsesOutline,
  BusinessOutline,
  LogOutOutline,
  PersonOutline
} from '@vicons/ionicons5'
import { useUserStore } from '../store/user'
import request from '../utils/request'
import message from '../utils/message'

const router = useRouter()
const userStore = useUserStore()

import { RouterLink } from 'vue-router'
// 菜单配置
const menuOptions = [
  {
    label: () =>
        h(
            RouterLink,
            {
              to: {
                name: 'home'
              }
            },
            { default: () => '首页' }
        ),
    key: '/',
    icon: () => h(HomeOutline)
  },
  // {
  //   label: '仲裁服务',
  //   key: '/arbitration',
  //   icon: () => h(DocumentTextOutline)
  // },
  // {
  //   label: '法律咨询',
  //   key: '/consultation',
  //   icon: () => h(ChatbubbleEllipsesOutline)
  // },
  // {
  //   label: '企业服务',
  //   key: '/business',
  //   icon: () => h(BusinessOutline)
  // }
]

function navigateToMenu(key) {
  router.push(key);
}



// 用户菜单选项
const userMenuOptions = [
  // {
  //   label: '个人中心',
  //   key: 'profile',
  //   icon: () => h(PersonOutline,{
  //     style: {
  //       width: '24px', // 设置图标宽度
  //       height: '24px' // 设置图标高度
  //     }
  //   })
  // },
  {
    label: '退出登录',
    key: 'logout',
    icon: () => h(LogOutOutline,{
      style: {
        width: '24px', // 设置图标宽度
        height: '24px' // 设置图标高度
      }
    })
  }
]

// 表单引用
const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 对话框显示状态
const showLoginModal = ref(false)
const showRegisterModal = ref(false)

// 加载状态
const loginLoading = ref(false)
const registerLoading = ref(false)

// 表单数据
const loginForm = ref({
  username: '',
  password: ''
})

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirmPassword: [
    { 
      required: true, 
      message: '请再次输入密码', 
      trigger: 'blur' 
    },
    {
      validator: (rule, value) => {
        return value === registerForm.value.password
      },
      message: '两次输入的密码不一致',
      trigger: 'blur'
    }
  ]
}

// 处理用户菜单选择
function handleUserMenuSelect(key) {
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loginLoading.value = true
    loginForm.value.type = "login"
    const response = await request.post('/api/user/login', loginForm.value)
    console.log("response--->",response)
    if (response.data.code != 200){
      message.error(response.data.message)
      return
    }
    userStore.setToken(response.data.data.token)
    console.log("token--->"+response.data.data.token)
    console.log("token userStore--->"+userStore.token)
    message.success('登录成功')
    showLoginModal.value = false
    loginForm.value = { username: '', password: '' }
  } catch (error) {
    if (!error.validation) { // 不是表单验证错误
      message.error(error.response?.data?.message || '登录失败')
    }
  } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    registerLoading.value = true

    const response  = await request.post('/api/user/login', {
      username: registerForm.value.username,
      password: registerForm.value.password,
      type:  "reg"
    })

    console.log("response--->",response)

    if (response.data.code != 200){
      message.error(response.data.message)
      return
    }
    message.success('注册成功，请登录')
    showRegisterModal.value = false
    registerForm.value = { username: '', password: '', confirmPassword: '' }
    showLoginModal.value = true
  } catch (error) {
     console.log("error+"+error.message)
    if (!error.validation) { // 不是表单验证错误
      message.error(error.response?.data?.message || '注册失败')
    }
  } finally {
    registerLoading.value = false
  }
}

// 处理退出登录
const handleLogout = () => {
  console.log("handleLogout---->")
  userStore.logout()
  // userStore.clearToken()
  // userStore.isLoggedIn = false
  message.success('已退出登录')
  router.push('/')
}

//更改当前的用户信息

</script>

<style scoped>
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #18a058;
}

.nav-menu {
  flex: 1;
  margin: 0 48px;
}

.user-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 24px;
  display: flex;
  justify-content: space-between;
}

.footer-section {
  flex: 1;
  margin: 0 24px;
}

.footer-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.footer-section p {
  margin: 8px 0;
  color: #666;
}

.copyright {
  text-align: center;
  padding: 16px 0;
  color: #999;
  border-top: 1px solid #eee;
}
</style>
